var tbody = document.querySelector('tbody')
var page = 1
var count = 5

function render(data) {
    tbody.innerHTML = ''
    data.map((item) => {
        tbody.innerHTML +=
            `<tr>
                <td>${item.email}</td>
                <td>${item.name}</td>
                <td class="phone">${item.phone}</td>
                <td>${item.is}</td>
                <td>${item.isadmin ? '是' : '否'}</td>
                <td>${item.status ? '健康' : '异常'}</td>
                <td><span class="bianji">编辑</span> <span class="shanchu">删除</span></td>
            </tr>`
    })
}


function render_data(page, count) {
    axios.get('/user/list', { params: { page: page, count: count } }).then((res) => {
        render(res.data.list)
    })
}
render_data(page, count)

var last = document.querySelector('h4 .last')
var next = document.querySelector('h4 .next')

last.onclick = () => {
    if (page > 1) {
        page--
        render_data(page, count)
    }
}
next.onclick = () => {
    if (page < 4) {
        page++
        render_data(page, count)
    }
}

var h3 = document.querySelector('.right h3')
var write = document.querySelector('#write')
h3.onclick = () => {
    write.classList.add('write')
    write.innerHTML =
        `<div class="write">
        <h1>注册</h1>
            <input type="text" placeholder="用户名">
            <input type="text" placeholder="密码">
            <input type="text" placeholder="确认密码">
            <input type="text" placeholder="邮箱">
            <input type="text" placeholder="名字">
        <button class="register">注册</button>
    </div>`
}

write.onclick = (e) => {
    if (e.target.classList == 'register') {
        var input = document.querySelectorAll('.write input')
        console.log(input);
        axios.post('/user/enroll', {
            phone: input[0].value,
            pass: input[1].value,
            email: input[3].value,
            name: input[4].value
        }).then((res) => {
            if (input[0].value) {
                if (input[1].value == input[2].value) {
                    if (res.data.code == 200) {
                        alert('注册成功')
                        write.innerHTML = ''
                        write.classList.remove('write')
                        render_data(page , count)
                    } else {
                        alert('账号已存在')
                    }
                } else {
                    alert('两次密码不一致')
                }
            }else {
                alert('手机号格式不正确')
            }
        })

    }
}

tbody.onclick = (e) => {
    var num = tbody.querySelectorAll('.phone')
    console.log(num);
    var shanchu = tbody.querySelectorAll('.shanchu')
    console.log(shanchu);
    shanchu.forEach((item , index) => {
        if(e.target == item){
            axios.post( '/user/delete' , {phone : num[index].innerText}).then((res)=>{
                render_data(page,count)
            })
        }
    } )
}
